package com.henary.annotation;

import com.henary.HasBean;
import com.henary.annotation.bean.Person;
import com.henary.annotation.bean.Shoes;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author henary
 * @date 2022年09月19日 13:55
 */
@Configuration
@ComponentScan(basePackages = "com.henary.annotation.bean")
@ImportResource(locations ="classpath:beans3.xml" )
@Import(value = {AnnotationConfig.ImportSelectorWithBook.class, AnnotationConfig.ImportBeanDefinitionRegistrarWithShoes.class})
@Profile("dev")
public class AnnotationConfig {

	@Bean
	@Conditional(value = {HasOneCondition.class})
	@HasBean
	public Person person() {

		return new Person("henary");
	}

	/*@Bean
	@Primary
	public Person person2() {
		return new Person("henary2");
	}*/

	static class HasOneCondition implements ConfigurationCondition {

		@Override
		public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
			MergedAnnotations annotations = metadata.getAnnotations();
			if (annotations.isPresent(HasBean.class)) {
				return true;
			}
			return false;
		}

		@Override
		public ConfigurationPhase getConfigurationPhase() {
			return ConfigurationPhase.REGISTER_BEAN;
		}
	}

	static class ImportSelectorWithBook implements ImportSelector {

		@Override
		public String[] selectImports(AnnotationMetadata importingClassMetadata) {
			String[] className = {"com.henary.annotation.bean.Book"};
			return className;
		}
	}

	static  class ImportBeanDefinitionRegistrarWithShoes implements ImportBeanDefinitionRegistrar{
		@Override
		public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
			GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
			beanDefinition.setBeanClass(Shoes.class);
			ConstructorArgumentValues argumentValues = new ConstructorArgumentValues();
			argumentValues.addIndexedArgumentValue(0,"nike");
			beanDefinition.setConstructorArgumentValues(argumentValues);
			registry.registerBeanDefinition("nikeShoes",beanDefinition);
		}
	}
}
